import Moment from "moment";
import { apiUrl } from "@/api/URLConfig";

import Canvas2Image from "@/unit/canvas2Image.js";
import html2canvas from "html2canvas";

function computeData(arr) {
  let size = JSON.stringify(arr).length;
  return `${size.toFixed(2)}`;
}

// 逗号分割字符串转 数组包含的 纯数字类型数组
function SwitchNumber(String) {
  let Arr = [];
  if (String !== "") {
    Arr = String.split(",");
    Arr = Arr.map(item => {
      return Number(item);
    });
  }
  return Arr;
}

// 递归
function FindObjFromList(list, key, value) {
  let obj = {};
  list.some(item => {
    if (item[key] == value) {
      obj = item;
      return true;
    }
    if (Array.isArray(item.childList) && item.childList.length) {
      obj = this.findObjFromList(item.childList, key, value);
      if (Object.keys(obj).length) {
        return true;
      }
    }
  });
  return obj;
}

// 获取当前后台的菜单
function getMenu(list, name) {
  let newRoutes = list.find(item => {
    return item.name == name;
  });
  return newRoutes.childList;
}

// 过滤不显示的路由菜单
function filterMenu(arr) {
  arr.forEach((item, index) => {
    if ((item.type == "2" && item.ifShow == "0") || item.type == "3") {
      // 如果找到,则跳出
      arr.splice(index, 1);
      return arr;
    }
    if (item.childList && item.childList.length) {
      const newArr = filterMenu(item.childList);
      if (newArr instanceof Array) {
        if (newArr.length > 0) {
          filterMenu(newArr);
        }
      }
    }
  });
  return arr;
}

// 过滤所有的页面路由
function filterRouters(lists, typeValue, arr = []) {
  lists.forEach(item => {
    let { name, path, pathName, type, childList, refresh, ifShow } = item;
    if (type == typeValue) {
      arr.push({
        path,
        name,
        type,
        refresh,
        component: () => import(`@/pages/${pathName}/index`),
        meta: {
          title: name,
          keepAlive: refresh === 1 ? true : false
        },
        ifShow
      });
    }
    if (childList && childList.length > 0) {
      return filterRouters(childList, typeValue, arr);
    }
  });
  return arr;
}

function getFirstMenuPath(lists, str = "") {
  if (lists.length > 0 && lists[0].type == "2") {
    str = lists[0].path;
  } else {
    return getFirstMenuPath(lists[0].childList, str);
  }
  return str;
}

function findTreePathLists(lists, activeMenuPath) {
  if (!(lists instanceof Array)) {
    return [];
  }
  if (lists.length == 0) {
    return [];
  }

  for (let i = 0; i < lists.length; i++) {
    const item = lists[i];
    if (item["path"] == activeMenuPath) {
      // 如果找到,则跳出
      return [item["id"]];
    }

    if (item.childList && item.childList.length) {
      const path = findTreePathLists(item.childList, activeMenuPath);
      if (path.length > 0) {
        // 字节点找到,把本节点插入到第一个
        path.splice(0, 0, item["id"]);
        return path;
      }
    }
  }
  return [];
}

// 获取某个页面下的子页面或者按钮
function getBtnListsOrPageLists(menuLists, pagePath, type) {
  let lists = getLists(menuLists, pagePath);
  let BtnListsOrPageLists = getItem(lists, type);
  return BtnListsOrPageLists;

  function getLists(lists, pagePath, arr = []) {
    for (let index in lists) {
      if (lists[index].path == pagePath) {
        arr = lists[index].childList;
        break;
      }
      if (lists[index].childList && lists[index].childList.length > 0) {
        arr = getLists(lists[index].childList, pagePath, arr);
      }
    }
    return arr;
  }

  function getItem(lists, type, arr = []) {
    for (let index in lists) {
      if (lists[index].type == type) {
        arr.push(lists[index]);
        // break;
      }
      if (lists[index].childList && lists[index].childList.length > 0) {
        arr = getItem(lists[index].childList, type, arr);
      }
    }
    return arr;
  }
}

// 树形结构递归添加自定义插槽
function setTreeData(arr, title, key) {
  let scopedSlots = { title };
  arr.forEach(item => {
    item.scopedSlots = scopedSlots;
    if (item[key] && item[key].length > 0) {
      item[key] = setTreeData(item[key], title, key);
    }
  });
  return arr;
}

function getFileAccessHttpUrl(avatar, subStr) {
  if (!subStr) subStr = "http";
  try {
    if (avatar && avatar.startsWith(subStr)) {
      return avatar;
    } else {
      if (avatar && avatar.length > 0 && avatar.indexOf("[") == -1) {
        return apiUrl + avatar;
      }
    }
  } catch (err) {
    return;
  }
}

// 获取当前页面id
function getPresentPageId(lists, activeMenuPath) {
  for (let i = 0; i < lists.length; i++) {
    let item = lists[i];
    if (item["path"] == activeMenuPath) {
      // 如果找到,则跳出
      return [item["id"]];
    }

    if (item.childList && item.childList.length) {
      const path = getPresentPageId(item.childList, activeMenuPath);

      if (path instanceof Array) {
        if (path.length > 0) {
          return path;
        } else {
          return [];
        }
      } else {
        getPresentPageId(item.childList, activeMenuPath);
      }
    }
  }
}
// 根据id查所有父级
function findTreePrevChainById(arr1, id) {
  let temp = [];
  const dp = (arr, id) => {
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      if (item.id === id) {
        temp.push(item);
        dp(arr1, item.parentId);
        break;
      } else {
        if (item.childList) {
          dp(item.childList, id);
        }
      }
    }
  };
  dp(arr1, id);
  return temp.reverse();
}

// 获取面包屑数据
function getBread(arr1, id) {
  let list = [];
  let Arr = findTreePrevChainById(arr1, id);
  Arr.forEach(item => {
    list.push(item.name);
  });
  return list;
}

// 获取商品类型对应是商品编码
function getCode(arr, children, id, key) {
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    if (item["id"] == id) {
      // 如果找到,则跳出
      return item[key];
    }

    if (item[children] && item[children].length) {
      const code = getCode(item[children], children, id, key);
      if (code) {
        // 字节点找到,把本节点插入到第一个
        return code;
      } else {
        getCode(item[children], children, id, key);
      }
    }
  }
}

// 表格日期格式化 年月日
function filterDate(time) {
  return Moment(time).format("YYYY-MM-DD");
}

// 监听local
function dispatchEventStroage() {
  const signSetItem = localStorage.setItem;
  localStorage.setItem = function(key, val) {
    let setEvent = new Event("setItemEvent");
    setEvent.key = key;
    setEvent.newValue = val;
    window.dispatchEvent(setEvent);
    signSetItem.apply(this, arguments);
  };
}

// html转换成图片
function savePoster(id, downloadName) {
  let that = this;
  //打开loading
  that.savePosterLoading = true;
  //生成图片之前，需先将整体的滚动条隐藏掉，否则生成出来的照片会偏移
  document.getElementById("app").style.overflowY = "hidden";
  //两个参数：所需要截图的元素id，截图后要执行的函数， canvas为截图后返回的最后一个canvas
  var shareContent = document.getElementById(id);
  var width = shareContent.offsetWidth;
  var height = shareContent.offsetHeight;
  var canvas = document.createElement("canvas");
  var scale = 5; //这里为了下载出更清晰的图片，值越大越清晰

  canvas.width = width * scale;
  canvas.height = height * scale;
  canvas.getContext("2d").scale(scale, scale);

  var opts = {
    scale: 1, //不管上面的scale是多少倍，这里只能取1，否则会显示不完全
    canvas: canvas,
    logging: true,
    width: width,
    height: height
  };
  html2canvas(shareContent, opts).then(function(canvas) {
    //这个方式是直接将canvas保存为图片的，具体参数可自行查看源码
    var img = Canvas2Image.saveAsImage(
      canvas,
      canvas.width,
      canvas.height,
      "PNG",
      downloadName
    );
    //这个方式只是提供展示图片的功能，暂时没有用到
    // var img = Canvas2Image.convertToPNG(canvas, canvas.width, canvas.height,'PNG');
    //  document.body.appendChild(img);

    //生成图片之前，需先将整体的滚动恢复为之前的状态
    document.getElementById("app").style.overflowY = "scroll";
    //关闭loading
    that.savePosterLoading = false;
  });
}

//  清楚keepalive缓存
const removeKeepAliveCacheForVueInstance = vueInstance => {
  let key =
    vueInstance.$vnode.key ??
    vueInstance.$vnode.componentOptions.Ctor.cid +
      (vueInstance.$vnode.componentOptions.tag
        ? `::${vueInstance.$vnode.componentOptions.tag}`
        : "");
  let cache = vueInstance.$vnode.parent.componentInstance.cache;
  let keys = vueInstance.$vnode.parent.componentInstance.keys;
  if (cache[key]) {
    vueInstance.$destroy();
    delete cache[key];
    let index = keys.indexOf(key);
    if (index > -1) {
      keys.splice(index, 1);
    }
  }
};

/**
 * 获取两个时间短之前的日期数组
 * @param {string} starDay
 * @param {string} endDay
 */
function getDayAll(starDay, endDay) {
  var arr = [];
  var dates = [];
  // 设置两个日期UTC时间
  var db = new Date(starDay);
  var de = new Date(endDay);

  // 获取两个日期GTM时间
  var s = db.getTime() - 24 * 60 * 60 * 1000;
  var d = de.getTime() - 24 * 60 * 60 * 1000;

  // 获取到两个日期之间的每一天的毫秒数
  for (var i = s; i <= d; ) {
    i = i + 24 * 60 * 60 * 1000;
    arr.push(parseInt(i));
  }
  // 获取每一天的时间  YY-MM-DD
  for (var j in arr) {
    var time = new Date(arr[j]);
    var year = time.getFullYear(time);
    var mouth =
      time.getMonth() + 1 >= 10
        ? time.getMonth() + 1
        : "0" + (time.getMonth() + 1);
    var day = time.getDate() >= 10 ? time.getDate() : "0" + time.getDate();
    var YYMMDD = year + "-" + mouth + "-" + day;
    dates.push(YYMMDD);
  }
  return dates;
}
export {
  computeData,
  SwitchNumber,
  FindObjFromList,
  filterRouters,
  getFirstMenuPath,
  getMenu,
  findTreePathLists,
  getBtnListsOrPageLists,
  setTreeData,
  getFileAccessHttpUrl,
  getPresentPageId,
  getBread,
  filterMenu,
  getCode,
  filterDate,
  dispatchEventStroage,
  savePoster,
  removeKeepAliveCacheForVueInstance,
  getDayAll
};
